package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import controller.action.Action;
import controller.action.DataParser;
import controller.util.ActionMapper;

public class ServiceController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static String rootPath = null;
	private Timer timer = null;
	private TimerTask timerTask = null;

	public ServiceController() {
		super();
	}

	public void init() throws ServletException {
		super.init();
		try {
			Class.forName("model.util.DBUtil");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		rootPath = getServletContext().getRealPath("WEB-INF");
		getServletContext().setAttribute("rootPath", rootPath);
		ActionMapper.mappingAction(rootPath+"/ActionMap.properties");

		System.out.println("init");
		timer = new Timer();
		timerTask = new TimerTask() {
			@Override
			public void run() {
				DataParser.NewsData();
				DataParser.RealTimeData();
				DataParser.WeatherData();
			}
		};
		timer.schedule(timerTask, 0, 1000000);
	}

	public void destroy() {
		timerTask.cancel();
		timer.cancel();
	}

	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("euc-kr");
		response.setContentType("text/html;charset=utf-8");
		request.setAttribute("rootpath", getServletContext().getAttribute("rootpath"));  //XMLBuilder 생성될 xml경로설정
		PrintWriter responseWriter = response.getWriter();
		String command = null;

		if ("XMLHttpRequest".equals(request.getHeader("x-requested-with"))) {
			command = request.getHeader("command");
		} else {
			command = request.getParameter("command");
		}
		System.out.println(command);
		Action action = ActionMapper.getAction(command);
		try {
			responseWriter.print(1);
			responseWriter.print(action.process(request, response));
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		}
	}
}
